package com.stx.openeyes.service;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.stx.openeyes.SealConst;
import com.stx.openeyes.model.Video;

import java.util.List;
import java.util.Random;

public class DownloadService extends Service {

    @Override
    public void onCreate() {
        Log.i("Kathy","onCreate - Thread ID = " + Thread.currentThread().getId());
        Gson mGson = new Gson();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    SharedPreferences settings = getSharedPreferences(SealConst.DOWNLOAN_VIDEOS, 0);
                    String infos = settings.getString(SealConst.DOWNLOAN_VIDEO_INFO, null);

                    if (infos == null)
                        return;

                    List<Video> videoList  = mGson.fromJson(infos, new TypeToken<List<Video>>() {
                    }.getType());
                    // 处理下载
                    if (videoList != null) {
                        for (Video video : videoList) {
                            if (video.getDownloanProgress() < 100) {
                                int r = new Random().nextInt(3);
                                if (video.getDownloanProgress() + r > 100) {
                                    video.setDownloanProgress(100);
                                } else {
                                    video.setDownloanProgress(video.getDownloanProgress() + r);
                                }
                            }
                        }
                        SharedPreferences.Editor editor = settings.edit();
                        editor.putString(SealConst.DOWNLOAN_VIDEO_INFO, mGson.toJson(videoList));
                        editor.commit();
                    }
                }
            }
        });
        thread.start();
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Kathy", "onStartCommand - startId = " + startId + ", Thread ID = " + Thread.currentThread().getId());
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i("Kathy", "onBind - Thread ID = " + Thread.currentThread().getId());
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i("Kathy", "onDestroy - Thread ID = " + Thread.currentThread().getId());
        super.onDestroy();
    }
}